<template>
	<div class="cardbox flex flex-v">
		<slot name="tablelist">
			<!--筛选条件-->
			<!-- :style="{ height: isShowFilterbar ? filterbarHeight + 'px' : 0 }" -->
			<div class="topbar" v-if="superQueryFieldList.length > 0" :class="{ active: isShowFilterbar }">
				<slot name="extraFilter"></slot>
				<div ref="filterbar" style="padding: 10px 16px">
					<filterbar
						ref="filterbars"
						@handlerSearch="handlerSearch"
						:showAllfieldList="showAllfieldList"
						@handlerReset="handlerReset"
						:field-list="superQueryFieldList"
						@changeSelect="changeSelect"
					></filterbar>
				</div>
			</div>
			<slot name="extraContent"></slot>
			<a-layout class="flex-1 wrapper" :style="{ paddingTop: superQueryFieldList.length > 0 ? '10px' : 0 }">
				<a-layout-sider
					v-if="hasLeftDept"
					class="leftsider"
					:width="collapsed ? 0 : siderWidth"
					:style="{
						marginRight: collapsed ? 0 : '10px',
					}"
				>
					<deptTree @selected="selectTree" :orgId="orgId"></deptTree>
					<img
						src="../../assets/img/arrow.png"
						class="arrow"
						:class="{ close: collapsed }"
						@click="collapsed = !collapsed"
					/>
				</a-layout-sider>
				<a-layout-content>
					<div class="main-wrapper flex flex-v">
						<div class="main-wrapper-hd flex flex-pack-justify flex-align-center">
							<template v-if="isRowSelection">
								<div class="selectedRowbar flex flex-align-center">
									<img src="../../assets/selecticon.png" />
									<span v-show="showresult" style="margin-right: 16px"
										>已选中{{ selectedRowKeys.length }}结果</span
									>
									<slot name="hd-button">
										<a-space :size="8">
											<template v-if="isDelete">
												<div class="line"></div>
												<a-button
													type="link"
													:disabled="selectedRowKeys.length <= 0"
													@click="delAllRecord(0)"
													><span>删除</span></a-button
												>
											</template>
										</a-space>
									</slot>
								</div>
							</template>
							<span v-else></span>
							<div class="toolbar flex flex-align-center">
								<slot name="toolbar">
									<a-space :size="23">
										<!-- <a-button class="ant-btn-blue" v-if="isImport" @click="importRecord"><span>导入</span></a-button>
										<a-button class="ant-btn-primary" v-if="isAdd" @click="addRecord()">
											<span class="iconfont icon-add"></span>
											<span>新增</span>
										</a-button>
										<a-button class="ant-btn-yellow" v-if="isReport" @click="exportRecord"><span>导出</span></a-button> -->

										<!-- 额外的操作按钮 -->
										<slot name="extendbtn"></slot>
										<a-button class="ant-btn-plain" v-if="isImport" @click="importRecord">
											<img :src="(isPro ? '/img_pro' : '/img') + '/import.png'" />
											<span>导入</span>
										</a-button>
										<a-button class="ant-btn-plain" v-if="isReport" @click="exportRecord">
											<img :src="(isPro ? '/img_pro' : '/img') + '/export.png'" />
											<span>导出</span>
										</a-button>
										<a-button class="ant-btn-primary" v-if="isAdd" @click="addRecord()">
											<img src="/img/add.png" />
											<span>新增</span>
										</a-button>
									</a-space>
								</slot>
							</div>
						</div>
						<ResizeObserver @resize="onResize">
							<div class="viewlist flex-1" ref="viewlist">
								<slot name="s-table">
									<!--表格-->
									<s-table
										:bordered="bordered"
										:columns="columnslist"
										:data="loadListData"
										:rowKey="rowKey"
										ref="table"
										:scroll="{ x: scrollx, y: showPagination ? scrolly : scrolly + 50 }"
										:rowSelection="
											isRowSelection
												? {
														selectedRowKeys: selectedRowKeys,
														onChange: onSelectChange,
														getCheckboxProps: (record) => ({
															props: {
																disabled: disabledKey
																	? record[disabledKey] == disabledValue
																	: false,
															},
														}),
												  }
												: null
										"
										:isFirstLoad="isFirstLoad"
										:pageSizeOptions="pageSizeOption"
										:showPagination="showPagination"
										:components="components"
									>
										<template
											v-for="column in columns"
											:slot="column.scopedSlots ? column.scopedSlots.customRender : ''"
											slot-scope="text, record, index"
										>
											<slot
												:name="column.scopedSlots ? column.scopedSlots.customRender : ''"
												v-bind="{ text, record, index }"
											></slot>
										</template>
									</s-table>
								</slot>
							</div>
						</ResizeObserver>
					</div>
				</a-layout-content>
			</a-layout>
		</slot>
		<slot></slot>
	</div>
</template>

<script>
import { mapState } from 'vuex';
import ResizeObserver from '@/components/vueSizeObserver';
import deptTree from '@/components/deptTree';
import { rowSelection, tableResize } from '@/mixins';
import { clearDeep, setColumnsSearchInfo, getColumnsSearchInfo } from '@/utils/base';
import { sysManageapi } from '@/api/index';
import Vue from 'vue';
import VueDraggableResizable from 'vue-draggable-resizable';
Vue.component('vue-draggable-resizable', VueDraggableResizable);
import QS from 'qs';
export default {
	name: 'proTable',
	data() {
		this.components = {
			header: {
				cell: (h, props, children) => {
					const { key, ...restProps } = props;
					const col = this.columns.find((col) => {
						const k = col.dataIndex || col.key;
						return k === key;
					});

					if (!col || !col.width) {
						return h('th', { ...restProps }, [...children]);
					}

					const dragProps = {
						key: col.dataIndex || col.key,
						class: 'table-draggable-handle',
						attrs: {
							w: 10,
							x: col.width,
							z: 1,
							axis: 'x',
							draggable: true,
							resizable: false,
						},
						on: {
							dragging: (x, y) => {
								col.width = Math.max(x, 1);
							},
						},
					};
					const drag = h('vue-draggable-resizable', { ...dragProps });
					return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag]);
				},
			},
		};
		return {
			setColumnsSearchInfo,
			breadList: [],
			filter: {},
			isShowFilterbar: true,
			checkedList: [],
			checkAll: true,
			hovered: false,
			tableData: [],
			siderWidth: 220,
			collapsed: false,
			selectedDeptId: '', // 选中部门Id
		};
	},
	mixins: [rowSelection, tableResize],
	components: {
		ResizeObserver,
		deptTree,
	},
	computed: {
		...mapState({
			isPro: (state) => state.isPro,
		}),
		getTitle() {
			return this.$route.meta.title;
		},
		superQueryFieldList() {
			if (this.columns && this.columns.length > 0) {
				let list = this.columns
					.filter(
						(item) =>
							(this.isAdmin || (!this.isAdmin && item.key != 'orgName') || !this.isHideOrgName) &&
							item.searchInfo
					)
					.map((item) => {
						let { key, title, searchInfo } = item;
						return Object.assign({}, { value: key, text: title }, searchInfo);
					});

				return list;
			} else {
				return [];
			}
		},
		columnslist() {
			if (this.columns && this.columns.length > 0) {
				let list = this.columns.filter(
					(item) =>
						this.checkedList.includes(item.key) &&
						(this.isAdmin || (!this.isAdmin && item.key != 'orgName') || !this.isHideOrgName)
				);

				return list;
			}
		},
	},

	props: {
		loadDataUrl: {
			type: String,
			default: '',
		},
		loadListFun: {
			type: Function,
			default: null,
		},
		columns: {
			type: Array,
			default: [],
		},
		showAllfieldList: {
			type: Boolean,
			default: false,
		},
		rowKey: {
			type: String,
			default: 'id',
		},
		isFirstLoad: {
			type: Boolean,
			default: true,
		},
		disabledKey: {
			type: String,
			default: '',
		},
		disabledValue: {
			type: [String, Number],
			default: '',
		},
		pageSizeOption: {
			type: Array,
			default: () => ['10', '20', '30', '40', '50', '100'],
		},
		showPagination: {
			type: String | Boolean,
			default: true,
		},
		isRowSelection: {
			type: Boolean,
			default: true,
		},
		bordered: {
			type: Boolean,
			default: false,
		},
		extendParam: {
			type: Object,
			default: null,
		},
		//是否有新增
		isAdd: {
			type: Boolean,
			default: true,
		},
		//是否有删除
		isDelete: {
			type: Boolean,
			default: true,
		},
		//是否导出
		isReport: {
			type: Boolean,
			default: false,
		},
		//是否导入
		isImport: {
			type: Boolean,
			default: false,
		},
		//是否显示工具栏
		isShowTotal: {
			type: Boolean,
			default: false,
		},

		//是否隐藏机构名称
		isHideOrgName: {
			type: Boolean,
			default: true,
		},
		//是否显示部门节点
		hasLeftDept: {
			type: Boolean,
			default: false,
		},
		//临时通过机构过滤部门
		orgId: {
			type: [String, Number],
			default: null,
		},
		//是否显示已选中结果
		showresult: {
			type: Boolean,
			default: true,
		},
		scrollx: {
			type: [Number, String],
			default: 1300,
		},
		//是否自定义筛选条件（比如点选）
		isDefinedFilter: {
			type: Boolean,
			default: false,
		},
	},
	created() {
		this.getBreadcrumb();
		let { $slots } = this;
		this.getCheckedList();
		// let checkedList = [];
		// if (this.columns && this.columns.length > 0) {
		// 	this.columns.forEach((item, index) => {
		// 		if (!item.hideInColumn) {
		// 			checkedList.push(item.key);
		// 			/* 如果是超级管理员，且机构筛选。这查询所有机构字段 */
		// 			if ((this.isAdmin || !this.isHideOrgName) && item.key == 'orgName' && item.searchInfo && item.searchInfo.type == 'select') {
		// 				this.getAllOrgList(index);
		// 			}
		// 		}
		// 	});
		// }
		// this.checkedList = [...checkedList];
	},

	watch: {
		columns: {
			// 数据变化时执行的逻辑代码
			handler(newName, oldName) {
				if (newName != oldName) {
					this.getCheckedList();
				}
			},
			// 开启深度监听
			deep: true,
			immediate: true,
		},
		orgId: {
			handler(newName, oldName) {
				if (newName != oldName) {
					if (!this.isDefinedFilter) {
						this.selectedDeptId = '';
						if (this.isAdmin) {
							let index = this.columns.findIndex(
								(item) =>
									item.key == 'deptName' && item.searchInfo && item.searchInfo.type == 'treeSelect'
							);
							if (index > -1) {
								this.getDeptTree(index);
							}
						}
					}
				}
			},
			immediate: false,
		},
	},
	methods: {
		//获取可展示列的key值
		getCheckedList() {
			let checkedList = [];
			if (this.columns && this.columns.length > 0) {
				this.columns.forEach((item, index) => {
					if (!item.hideInColumn) {
						checkedList.push(item.key);
						/* 如果是超级管理员，且机构筛选。则查询所有机构字段 */
						if (
							(this.isAdmin || !this.isHideOrgName) &&
							item.key == 'orgName' &&
							item.searchInfo &&
							item.searchInfo.type == 'select'
						) {
							this.getAllOrgList(index);
						}
						if (
							this.isAdmin &&
							item.key == 'deptName' &&
							item.searchInfo &&
							item.searchInfo.type == 'treeSelect'
						) {
							this.getDeptTree(index);
						}
					}
				});
				//隐藏操作列
				if (this.isHideOperateColumn) {
					checkedList = checkedList.filter((item) => item != 'operation');
				}
			}
			this.checkedList = [...checkedList];
		},
		getBreadcrumb() {
			this.breadList = [];
			this.name = this.$route.name;
			this.$route.matched.forEach((item) => {
				this.breadList.push(item);
			});
		},
		/* 筛选 */
		handlerSearch(obj) {
			console.log('检索', obj);
			this.resetSelectedRowKeys();
			/* 过滤掉空对象 */
			clearDeep(obj);
			/* 判断有没有筛选的拦截 */
			const handlerSearch = this.$listeners['handlerSearch'];
			if (handlerSearch && typeof handlerSearch === 'function') {
				handlerSearch(obj);
			} else {
				this.loadTable(obj);
			}
		},
		/* 重置 */
		handlerReset(obj) {
			// 将部门变量置空
			this.selectedDeptId = '';
			const handlerReset = this.$listeners['handlerReset'];
			if (handlerReset && typeof handlerReset === 'function') {
				handlerReset(obj);
			} else {
				this.handlerSearch(obj);
			}
		},
		/* 重置列表 */
		loadTable(obj) {
			this.filter = obj;
			this.handlerRefresh();
		},
		/* 刷新列表 */
		handlerRefresh(type) {
			this.resetSelectedRowKeys();
			this.$refs.table.refresh(type);
		},
		/* 清空选中的checkbox */
		resetSelectedRowKeys() {
			this.onSelectChange([]);
		},
		loadListData(parameter) {
			if (this.loadListFun) {
				return this.loadListFun(parameter);
			} else if (this.loadDataUrl) {
				let param = Object.assign(
					{},
					this.selectedDeptId
						? {
								deptId: this.selectedDeptId,
						  }
						: null,
					this.extendParam ? this.extendParam : {},
					parameter,
					this.filter
				);
				param = Object.keys(param).length > 0 ? param : null;
				let loadUrl = this.loadDataUrl;
				return this.$postAction(loadUrl, param).then((res) => {
					this.tableData = !!res.data ? res.data.list || res.data : [];
					const setTableData = this.$listeners['setTableData'];
					if (setTableData && typeof setTableData === 'function') {
						setTableData(this.tableData);
					}
					return !!res.data
						? res.data
						: !!this.showPagination
						? {
								list: [],
								total: 0,
						  }
						: [];
				});
			}
		},
		onAllChange(e) {
			Object.assign(this, {
				checkedList: e.target.checked ? this.columns.map((item) => item.key) : [],
				checkAll: e.target.checked,
			});
		},
		onChange(checkedList) {
			this.checkAll = checkedList.length === this.columns.length;
		},
		onRest() {
			Object.assign(this, {
				checkedList: this.columns.map((item) => item.key),
				checkAll: true,
			});
		},
		handleHoverChange(visible) {
			this.hovered = visible;
		},
		getTableData() {
			return this.tableData;
		},
		getAllOrgList(index) {
			this.$postAction(sysManageapi.orgUrl.getAllList).then((res) => {
				if (res && res.code == 1) {
					let orgList = res.data;
					if (orgList) {
						let list = orgList.map((item) => {
							return {
								value: item.orgId,
								text: item.orgName,
							};
						});

						this.columns[index].searchInfo.optionlist = [...list];
					}
				}
			});
		},
		//获取部门
		getDeptTree(index) {
			this.confirmLoading = true;
			this.$postAction(sysManageapi.deptUrl.getDeptList, {
				orgId: this.orgId || null,
			})
				.then((res) => {
					if (res && res.code == 1) {
						let deptList = [...res.data];
						if (deptList) {
							if (!index && index != 0) {
								index = this.columns.findIndex((item) => item.key == 'deptName');
								this.$emit('clearDept', index);
							}
							console.log('index', index, this.columns);
							this.columns[index].searchInfo.optionlist = [...deptList];
						}
					}
				})
				.finally(() => {
					this.confirmLoading = false;
				});
		},
		addRecord() {
			this.$emit('addRecord');
		},
		delAllRecord(type) {
			this.$emit('showDeleteConfirm', type);
		},
		//导入
		importRecord() {
			this.$emit('importRecord');
		},
		//导出
		exportRecord() {
			this.$emit('exportRecord');
		},
		//筛选条件下拉
		changeSelect(e, value, item) {
			// 如果下拉是机构
			if (value == 'orgId') {
				// 清空所选部门
				this.selectedDeptId = '';
				// 如果机构值清除
				this.filter.orgId = e;
			}
			this.$emit('changeSelect', e, value, item);
		},
		/* 选中部门，刷新列表 */
		selectTree(selectedDept) {
			// 每次置空一次
			this.selectedDeptId = '';
			const handlerDeptTree = this.$listeners['handlerDeptTree'];
			if (handlerDeptTree && typeof handlerDeptTree === 'function') {
				handlerDeptTree(selectedDept);
			} else {
				selectedDept = !!selectedDept ? { ...selectedDept } : null;
				this.selectedDeptId = !!selectedDept ? selectedDept.deptId : '';
				this.$nextTick(() => {
					this.handlerRefresh();
				});
			}
		},
	},
};
</script>

<style lang="less" scoped>
.wrapper {
	position: relative;
	padding: 0;
	height: 100%;
	padding: 20px 0 0 0;
}

.breadcrumb {
	// margin-bottom: 10px;
}

.pagehd {
	overflow: hidden;
	border-bottom: none;
	background: #fafbff;
	padding: 0 24px 10px;
	margin: 0 -10px 0;
	text-align: left;
	position: relative;
}

.pagehd:after {
	content: '';
	height: 1px;
	position: absolute;
	left: 24px;
	right: 24px;
	bottom: 0;
	background: #ddd;
}

.hd-right {
	float: right;
}
/deep/ .handlerbtn {
	min-width: 250px;
	text-align: right;

	.ant-btn {
		margin: 0 10px;
	}
}

/deep/ .topbar {
	background: #fff;
	z-index: 6;
	box-shadow: 0px 4px 8px rgba(19, 29, 53, 0.05);
	/* border-radius: 4px;
	box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.25); */
	border-radius: 8px;
	margin: 0;
	transition: all 0.3s;
	f
	// overflow: hidden;
	& > div {
		padding: 10px 16px;
	}
}

/deep/ .viewlist {
	min-height: 0;
	overflow: hidden;
	padding: 0 16px;

	/deep/ .ant-card-body {
		padding: 0 14px;
		height: 100%;
	}

	/deep/ .ant-pagination-total-text {
		position: absolute;
		left: 8px;
	}
}

.cardbox {
	overflow: auto;
	height: 100%;
	margin-top: 15px;
}

/deep/ .ant-btn {
	padding: 0 12px;
}
/deep/ .ant-btn > .anticon + span,
/deep/ .ant-btn > span + .anticon {
	margin-left: 4px;
}
/deep/ .main-wrapper {
	background: #fff;
	overflow: hidden;
	box-shadow: 0px 4px 8px rgba(19, 29, 53, 0.05);
	border-radius: 8px;
	height: calc(100% - 30px);
	.main-wrapper-hd {
		padding: 16px;
	}
}
// /deep/.main-wrapper-hd {
// 	.selectedRowbar {
// 		border: 1px solid #e0e5ef;
// 		height: 36px;
// 		border-radius: 4px;
// 		padding: 10px 12px;
// 		color: #1e2d2a;
// 		img {
// 			margin-right: 12px;
// 		}
// 		.line {
// 			width: 1px;
// 			height: 9px;
// 			background: #b3b3b3;
// 		}
// 		.ant-btn-link {
// 			color: #747776;
// 		}
// 		.ant-btn-link[disabled] {
// 			color: rgba(0, 0, 0, 0.25);
// 		}
// 	}
// 	.toolbar {
// 		.ant-btn-blue,
// 		.ant-btn-green,
// 		.ant-btn-yellow,
// 		.ant-btn-primary {
// 			width: 68px;
// 			height: 32px;
// 			border-radius: 4px;
// 			font-size: 14px;
// 			span {
// 				vertical-align: middle;
// 			}
// 			.iconfont {
// 				font-size: 10px;
// 			}
// 			.iconfont + span {
// 				margin-left: 4px;
// 			}
// 		}
// 	}
// }

/deep/.main-wrapper-hd {
	.selectedRowbar {
		border: 1px solid #e0e5ef;
		height: 36px;
		border-radius: 4px;
		padding: 10px 12px;
		color: rgba(46, 36, 36, 0.6);
		img {
			margin-right: 12px;
		}
		.line {
			width: 1px;
			height: 9px;
			background: #eeeeee;
		}
		.ant-btn-link {
			color: rgba(46, 36, 36, 0.6);
		}
		.ant-btn-link[disabled] {
			color: rgba(0, 0, 0, 0.25);
		}
	}
	.toolbar {
		margin-left: 10px;
		justify-content: flex-end;
		.ant-btn {
			min-width: 68px !important;
			height: 30px;
			border-radius: 4px;
			font-size: 14px;
			//padding: 0 15px !important;

			&.ant-btn-plain {
				background: #fff;
				color: @primary-color;
				border: 1px solid @primary-color;
			}
			img {
				vertical-align: -0.125em;
				width: 12px;
				height: auto;
				margin-right: 4px;
			}
		}
	}
}
.ant-table td {
	white-space: nowrap;
}

.leftsider {
	background: #fff;
	position: relative;
	margin: 0 10px 0 0;
	border-radius: 8px;
	.arrow {
		position: absolute;
		top: 50%;
		left: calc(100% - 10px);
		z-index: 999;
		transform: translate(0, -50%);
		cursor: pointer;
		&.close {
			transform: translate(0, -50%) scaleX(-1);
			left: 100%;
		}
	}
}
/deep/ .resize-table-th {
	position: relative;
	.table-draggable-handle {
		transform: none !important;
		position: absolute;
		height: 100% !important;
		bottom: 0;
		left: auto !important;
		right: -5px;
		cursor: col-resize;
		touch-action: none;
	}
}
</style>
